﻿using Inovout.Runtime;
using Inovout.Web;
using System;
using System.Linq;
using System.Web.Mvc;

namespace Inovout.Cloud.Web.Mvc
{
    public static class CloudUrlExtensions
    {
        public static string ActionByProject(this UrlHelper urlHelper, string actionName, string controllerName)
        {
            return urlHelper.Action(actionName, controllerName, new { projectId = urlHelper.RequestContext.HttpContext.Request.QueryString["projectId"] });
        }
        public static string ActionInApplication(this UrlHelper urlHelper, string applicationName)
        {
            var productConfiguration = ((WebApplication)ComponentRegistry.Resolve<IApplication>()).ProductConfiguration;
            UriBuilder uriBuilder = new UriBuilder(productConfiguration.Children[0].Children.Single(c => c.Attributes["name"].Equals(applicationName)).Attributes["url"]);
            if (string.IsNullOrEmpty(uriBuilder.Query))
            {
                uriBuilder.Query="projectId="+urlHelper.RequestContext.HttpContext.Request.QueryString["projectId"];
            }
            else
            {
                uriBuilder.Query = "&projectId=" + urlHelper.RequestContext.HttpContext.Request.QueryString["projectId"];
            }
            return uriBuilder.ToString();
        }

        public static string ActionInApplication(this UrlHelper urlHelper,string actionName, string controllerName, string applicationName)
        {
            var productConfiguration = ((WebApplication)ComponentRegistry.Resolve<IApplication>()).ProductConfiguration;
            UriBuilder uriBuilder = new UriBuilder(productConfiguration.Children[0].Children.Single(c => c.Attributes["name"].Equals(applicationName)).Attributes["url"]);
            uriBuilder.Path = controllerName + "/" + actionName;
            if (string.IsNullOrEmpty(uriBuilder.Query))
            {
                uriBuilder.Path = controllerName + "/" + actionName;
                uriBuilder.Query = "projectId=" + urlHelper.RequestContext.HttpContext.Request.QueryString["projectId"];
            }
            else
            {
                uriBuilder.Query = "&projectId=" + urlHelper.RequestContext.HttpContext.Request.QueryString["projectId"];
            }
            return uriBuilder.ToString();
        }
    }
}
